package com.atguigu.daijia.dispatch.xxl.job;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.daijia.dispatch.service.NewOrderService;
import com.atguigu.daijia.model.entity.dispatch.XxlJobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @create: 2024/9/25
 * @author: gyhe10
 * @description: 任务执行方法
 **/

@Slf4j
@Component
@RequiredArgsConstructor
public class JobHandler {

    private final NewOrderService newOrderService;
    private final XxlJobLogMapper xxlJobLogMapper;

    @XxlJob("newOrderTaskHandler")
    public void newOrderTaskHandler() {
        log.info("新订单的定时任务 ID：{}", XxlJobHelper.getJobId());

        // 记录定时任务日志信息
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        // 开始时间
        long startTime = System.currentTimeMillis();

        try {
            // 执行新订单的定时任务：每分钟执行一次，查询附近可以接单的司机，推送新订单信息到司机的临时队列
            newOrderService.executeNewOrderTask(XxlJobHelper.getJobId());
            xxlJobLog.setStatus(1);// 执行成功
        } catch (Exception e) {
            xxlJobLog.setStatus(0);// 执行失败
            xxlJobLog.setError(ExceptionUtil.getAllExceptionMsg(e));
            log.error("执行新订单定时调度任务失败，任务 ID：{}", XxlJobHelper.getJobId());
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.XXL_JOB_FAIL);
        } finally {
            long times = System.currentTimeMillis() - startTime;
            xxlJobLog.setTimes(times);
            xxlJobLogMapper.insert(xxlJobLog);
        }
    }
}
